package com.woke.addressactivity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.WriterException;
import com.http.HttpMethods;
import com.woke.method.MyApp;
import com.zhongcai.online.R;
import com.zxing.encoding.EncodingHandler;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import cn.xl.xxl.imagecache.ImageLoader;

public class Userinfo_payActivity extends Activity {

    private ImageView mIermae;

    private MyApp myapp;

    private ImageLoader imageLoader;
    private int screenHigth, screenWidth;
    private TextView title, text_money, avpay_type;
    private String url, payWay, money, userId;
    private int channelWay;//支付渠道 新增3.16
    private View mProgress;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alipapapay);

        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll()
                    .build();
            StrictMode.setThreadPolicy(policy);
        }

        imageLoader = new ImageLoader(this);
        myapp = (MyApp) getApplication();
        screenHigth = myapp.screenHigth;
        screenWidth = myapp.screenWidth;
        title = (TextView) findViewById(R.id.avsqb_title_text);
        mIermae = (ImageView) this.findViewById(R.id.avpay_image_code);
        text_money = (TextView) findViewById(R.id.avpay_text_monye);
        avpay_type = (TextView) findViewById(R.id.avpay_text_therrtype);
        mProgress = findViewById(R.id.avalipay_frame);
        LayoutParams params = mIermae.getLayoutParams();
        params.width = screenWidth / 5 * 4;
        params.height = screenWidth / 5 * 4;
        mIermae.setLayoutParams(params);
        findViewById(R.id.avsqb_image_back).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                finish();
            }
        });
        // 读取数据
        Intent intent = getIntent();
        payWay = intent.getStringExtra("payWay");
        money = intent.getStringExtra("money");
        userId = intent.getStringExtra("userId");
        channelWay = intent.getIntExtra("channelWay", -1);
        if (payWay.equals("1")) {
            title.setText("微信收款");
            avpay_type.setText("微信扫一扫，向我付款");
        } else {
            title.setText("支付宝收款");
            avpay_type.setText("支付宝扫一扫，向我付款");
        }
        text_money.setText("￥" + money);


        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                dopost(payWay, money);
            }
        }).start();

        mProgress.setVisibility(View.VISIBLE);
    }

    private void dopost(String payWay, String totalAmount) {

        // 封装数据
        Map<String, String> parmas = new HashMap<String, String>();
        parmas.put("userId", userId);
        parmas.put("payWay", payWay);
        parmas.put("way", String.valueOf(channelWay));
        parmas.put("totalAmount", totalAmount);
        Log.e("11111", userId + "\n" + payWay + "\n" + channelWay + "\n" + totalAmount);

        DefaultHttpClient client = new DefaultHttpClient();// http客户端
        HttpPost httpPost = new HttpPost(HttpMethods.BASEURL
                + "g=Api&m=Gallerychoose&a=choosePaySmServlet");
        ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
        if (parmas != null) {
            Set<String> keys = parmas.keySet();
            for (Iterator<String> i = keys.iterator(); i.hasNext(); ) {
                String key = (String) i.next();
                pairs.add(new BasicNameValuePair(key, parmas.get(key)));
            }
        }

        try {
            UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(pairs,
                    "utf-8");

            // 将POST数据放入HTTP请求

            httpPost.setEntity(p_entity);

            // 发出实际的HTTP POST请求

            HttpResponse response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            String returnConnection = convertStreamToString(content);
            System.out.println("returnConnection============="
                    + returnConnection);
            // {"flag":"success","info":"OK","data":{"data":"weixin:\/\/wxpay\/bizpayurl?pr=5ocvA51"},"time":1482751227}
            try {
                JSONObject jsonObject = new JSONObject(returnConnection);
                final String flag = jsonObject.getString("flag");
                if (flag.equals("success")) {
                    JSONObject json = jsonObject.getJSONObject("data");
                    url = json.getString("data");

                    Message msg = new Message();
                    Bundle data = new Bundle();
                    data.putString("url", url);
                    msg.setData(data);
                    handler.sendMessage(msg);

                } else if (flag.equals("unknow")) {
                    String info = jsonObject.getString("info");
                    Message msg = new Message();
                    Bundle data = new Bundle();
                    data.putString("url", "");
                    data.putString("info", info);
                    msg.setData(data);
                    handler.sendMessage(msg);
                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block

                e.printStackTrace();
            }

        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String convertStreamToString(InputStream content) {

        // TODO Auto-generated method stub
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                content));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                content.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            mProgress.setVisibility(View.GONE);
            Bundle data = msg.getData();
            url = data.getString("url");
            if (url == "") {
                String info = data.getString("info");
                Toast.makeText(Userinfo_payActivity.this, info, Toast.LENGTH_LONG).show();
                finish();
            } else {
                setCodeImage();
            }
        }
    };

    private void setCodeImage() {
        try {

            if (!url.equals("")) {

                Bitmap qrCodeBitmap = EncodingHandler.createQRCode(url, 350);
                mIermae.setImageBitmap(qrCodeBitmap);
            } else {
                Toast.makeText(Userinfo_payActivity.this, "Text can not be empty", Toast.LENGTH_SHORT)
                        .show();
            }

        } catch (WriterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}
